<template>
  <div class="wrapper wrapper-content animated fadeInRight v-cloak" v-cloak>
    <div class="col-md-12">
      <form @submit.prevent="update()" accept-charset="UTF-8" class="form m-t" id="authRoleForm" method="post">
        <input name="id" type="hidden" v-model="item.id"/>
        <input name="token" type="hidden" v-model="item.uuidToken"/>
        <input :value="newFlag!=0?0:1" name="newFlag" type="hidden"/>
        <div class="clearfix "></div>
        <div class="col-sm-3">
          <div class="form-group clearfix">
            <label class="col-md-8 control-label">角色：
              <input required="" aria-describedby="bean-name-error" aria-invalid="true" class="form-control" id="bean-name" maxlength="55" name="name" placeholder="请输入角色" type="text" v-model="item.name">
            </label>
          </div>
          <div class="form-group clearfix">
            <label class="col-md-12 control-label">备注：
              <input aria-describedby="bean-memo-error" aria-invalid="true" class="form-control" id="bean-memo" maxlength="255" name="memo" placeholder="请输入备注" type="text" v-model="item.memo">
            </label>
          </div>
          <div class="col-12 text-center" style="height: 50px;">
            <div style="width: 200px; margin: 0 auto;text-align: center;">
              <input class="btn btn-primary" type="submit" value="保存"/> | <a @click="lbox.closeMyBoxLayer()" class="btn btn-danger" href="javascript:">返回</a>
            </div>
          </div>
        </div>
        <div class="col-sm-6">
          <div class="form-group clearfix">
            <!--                <label class="col-md-3 control-label">系统权限：</label>-->
            <div class="col-md-12">
              <div class="col-sm-8">
                <ul class="ztree" id="tree"></ul>
              </div>
              <div id="treeFormContent">
                <input :id="perm.id" :value="perm.id" name="permIds" type="hidden" v-for="(perm, index) in rolePermNodes"/>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script type="text/javascript">
  import '@/assets/css/style.css'

  import $ from '@/assets/js/jquery-vendor.js'
  import 'jquery.cookie'
  import axios from 'axios'
  import '@/assets/js/validate/validation-vendor.js'
  import 'ztree'
  import '@/assets/css/zTree.css'
  import {$storage, apiUtil, axiosContentType, site, zTreeBridge} from '@/assets/js/boss'

  let zTreeObj;

  export default {
    data() {
      return {
        item: {}, uuidToken: '', newFlag: 0, permNodes: [], rolePermNodes: []
      }
    },
    mounted() {
      let that = window.$vueApp = this;
      document.getElementsByTagName('body')[0].className = 'fixed-sidebar full-height-layout';
      that.staff.init(() => {
        $('#authRoleForm').validate();
        if (apiUtil.existSessionKey(site.authRole.info)) {
          that.info();
        }
        that.permTree();
      });
    },
    methods: {
      info() {
        let that = this;
        axios.post(site.authRole.info + $storage.getItem(site.authRole.info), {}).then(function (response) {
          const result = response.data;
          if (result.code === 0) {
            that.item = result.data;
          } else {
            alert(result.message);
          }
        });
      },
      permTree() {
        let that = this;
        axios.post(site.authPerm.tree, {}
          , axiosContentType.xWwwFormUrlencoded).then(function (response) {
          const result = response.data;
          if (result.code === 0) {
            that.permNodes = result.data;
            zTreeObj = $.fn.zTree.init($('#tree'), {
              check: zTreeBridge.checkbox,
              callback: {onCheck: that.onCheck}
            }, zTreeBridge.getAndSetTreeRoot(result.data));
            zTreeObj.expandAll(true);
            that.rolePermList();
          } else {
            alert(result.message);
          }
        }, 'json');
      },
      onCheck(e, treeId, treeNode) {
        if (treeNode.checked) {
          if ($(`#treeFormContent #${(treeNode && treeNode.id)}`).length === 0) {
            this.appendPerm(treeNode);
          }
        } else {
          this.removePerm(treeNode);
        }
      },
      getPermNode(permNode, treeNode) {
        if (treeNode && (treeNode && treeNode.id) && permNode && permNode.id === (treeNode && treeNode.id)) {
          zTreeObj.checkNode(treeNode, true, false);
          return true;
        } else if (treeNode && treeNode.id !== 'root' && !this.staff.hasPermission(treeNode.matchStr)) {
          treeNode.chkDisabled = true
          if (treeNode instanceof Array || Object.prototype.toString.call(treeNode) === '[object Array]') {
            zTreeObj.removeChildNodes(treeNode);
          } else {
            zTreeObj.removeNode(treeNode);
          }
        }
        if (treeNode instanceof Array || Object.prototype.toString.call(treeNode) === '[object Array]') {
          // console.info('array=treeNode=' + JSON.stringify(treeNode))
          for (let i = 0; i < treeNode.length; i++) {
            this.getPermNode(permNode, treeNode[i]);
          }
        } else if (treeNode.children) {
          for (let i = 0; i < treeNode.children.length; i++) {
            this.getPermNode(permNode, treeNode.children[i]);
          }
        }
      },
      appendPerm(treeNode) {
        if (treeNode) {
          $('#treeFormContent').append('<input type="hidden" id="' + (treeNode && treeNode.id) + '" name="permIds" value="' + (treeNode && treeNode.id) + '" />');
        }
      },
      removePerm(treeNode) {
        if (treeNode) {
          $('#' + (treeNode && treeNode.id)).remove();
        }
      },
      rolePermList() {
        let that = this;
        that.rolePermNodes = [];
        axios.post(site.authRole.perm, 'roleId=' + $storage.getItem(site.authRole.info)
          , axiosContentType.xWwwFormUrlencoded).then(function (response) {
          const result = response.data;
          // console.info("获取数据.." + JSON.stringify(result));
          if (result.code === 0) {
            that.rolePermNodes = result.data;
            if (that.rolePermNodes && that.rolePermNodes.length > 0) {
              for (let i = 0; i < that.rolePermNodes.length; i++) {
                that.getPermNode(that.rolePermNodes[i], zTreeObj.getNodes());
              }
            }
          } else {
            alert(result.message);
          }
        }, 'json');
      },
      update() {
        let that = this;
        if ($('#authRoleForm').valid()) {
          axios.post(site.authRole.update, $('#authRoleForm').serialize()
            , axiosContentType.xWwwFormUrlencoded).then(function (response) {
            const result = response.data;
            if (result.code === 0) {
              parent.$vueApp.page();
              alert('保存成功!');
              that.lbox.closeMyBoxLayer()
            } else {
              alert(result.message);
            }
          });
        }
      }
    }
  }
</script>

